import { encrypt, decrypt } from 'salteen'

const MY_SALT = 'weizukeji'
const ENCODER = encrypt(MY_SALT)
const DECODER = decrypt(MY_SALT)

export const crypt = {
  encode: (str: string) => {
    return ENCODER(encodeURIComponent(str))
  },
  decode: (str: string) => {
    return decodeURIComponent(DECODER(str))
  }
}

export function trim(str: string) {
  return str.trim()
}

export const getUnique = (num?: number) => {
  const res = Math.random().toString().split('.')[1]
  if (num) {
    return res.slice(0, num)
  } else {
    return res
  }
}

export function createCookie(
  name: string,
  value: string,
  days?: number,
  path?: string,
  domain?: string,
  secure?: string
) {
  let expires = ''
  if (days) {
    let date = new Date()

    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)

    expires = date.toUTCString()
  } else expires = ''

  let cookieString = name + '=' + trim(value)

  if (expires) cookieString += ';expires=' + expires

  if (path) cookieString += ';path=' + trim(path)

  if (domain) cookieString += ';domain=' + trim(domain)

  if (secure) cookieString += ';secure=' + trim(secure)

  document.cookie = cookieString
}

export function getAccessToken() {
  const key = 'agent-token'
  return sessionStorage.getItem(key) || localStorage.getItem(key) || getCookie(key)
}

export function setAccessToken(value: string, lasting: boolean) {
  const key = 'agent-token'
  sessionStorage.setItem(key, value)
  localStorage.setItem(key, value)
  setCookie(key, value, getDomain(), lasting)
}

export function clearAccessToken() {
  clearStorage()
  const domain = getDomain()
  const key = 'agent-token'
  document.cookie = key + '=0;expires=' + new Date(0).toUTCString()
  document.cookie = key + '=0;domain=' + domain + ';expires=' + new Date(0).toUTCString()
  document.cookie = key + '=0;path=/;domain=' + domain + ';expires=' + new Date(0).toUTCString()
}

export function getCookie(name: string) {
  const cookies = document.cookie
  if (cookies) {
    const cookieObj: any = {}
    cookies.split(';').forEach(item => {
      const [key, value] = item.split('=')
      cookieObj[trim(key)] = trim(value)
    })

    if (cookieObj[name]) {
      return cookieObj[name]
    } else {
      return ''
    }
  } else {
    return ''
  }
}

export function CheckOptionAuth(routeList: any[], authList: string[]) {
  const resList: any[] = []
  routeList.forEach(route => {
    if (!route.auth || authList.includes(route.auth)) {
      const routeItem = { ...route }
      if (route.routes && route.routes.length) {
        routeItem.routes = CheckOptionAuth(route.routes, authList)
      }

      resList.push(routeItem)
    }
  })

  return resList
}

export function findPath(path: string, routes: any[], authList: string[]): any {
  let res = null

  routes.forEach(item => {
    if (item.path === path) {
      res = item
    } else {
      if (item.routes) {
        const tempRes = findPath(path, item.routes, authList)
        if (tempRes) {
          res = tempRes
        }
      }
    }
  })

  return res
}

export function findPathAuth(path: string, routes: any[], authList: string[]) {
  const res = findPath(path, routes, authList)
  if (!res.auth || authList.includes(res.auth)) {
    return true
  } else {
    return false
  }
}

export const changeFavicon = (faviconUrl: string) => {
  const eleList = Array.from(document.head.children)

  const favLink: any = eleList.find((item: any) => item.rel === 'shortcut icon')
  if (favLink) {
    favLink.href = faviconUrl
  }
}

export const getDomain = () => {
  let domain = window.location.hostname
  const domainList = window.location.hostname.split('.')
  if (domainList.length > 2) {
    domain = domainList.splice(1).join('.')
  }
  return domain
}

export const clearCookie = () => {
  const oKeys = document.cookie.match(/[^=;]+(?=\=)/g)
  const keys = oKeys ? oKeys.map(i => trim(i)) : []
  if (keys) {
    const domain = getDomain()
    keys.forEach(key => {
      document.cookie = key + '=0;expires=' + new Date(0).toUTCString()
      document.cookie = key + '=0;domain=' + domain + ';expires=' + new Date(0).toUTCString()
      document.cookie = key + '=0;path=/;domain=' + domain + ';expires=' + new Date(0).toUTCString()
    })
  }
}

export const clearStorage = () => {
  localStorage.clear()
  sessionStorage.clear()
}

export const clearLogin = () => {
  clearStorage()
  clearCookie()
}

export const getSortType = (sortType: string) => {
  const map: any = {
    ascend: 'asc',
    descend: 'desc'
  }
  return map[sortType]
}

export const isDot = (num: number) => {
  return String(num).indexOf('.') > -1
}

export const setQueryParams = (params: any) => {
  if (params) {
    const list = Object.keys(params).filter(item => params[item])
    if (list && list.length) {
      let str = '?'
      list.forEach((item, index) => {
        str += `${index ? '&' : ''}${item}=${params[item]}`
      })
      return str
    }
  }
  return ''
}

export const routeFormat = (list: any) => {
  let arr =  list.map((item: any) => ({
    name: item.menu_name,
    path: item.path === '#' ? `/${Math.floor(Math.random() * 1000000000)}` : item.path,
    // component: './UserSum',
    // component: item.path === '#' ? null : item.path,
    icon_: item.menu_icon,
    routes: item.children ? routeFormat(item.children) : null,
    id: item.id,
    pid: item.menu_pid
  }))
  return arr
}

export const setCookie = (name: string, value: string, domain: string, keep?: boolean) => {
  let cookie_string = name + '=' + value

  if (keep) {
    const now = new Date()
    now.setFullYear(now.getFullYear() + 1)
    const expires = now.toUTCString()

    cookie_string += '; expires=' + expires
  }

  cookie_string += '; path=/'

  if (domain) cookie_string += '; domain=' + domain
  document.cookie = cookie_string
}